package repository

import (
	"energy-amiot-platform/model/dbspo"

	"gorm.io/gorm"
)

var (
	PRODUCT productRpo
)

type productRpo struct {
}

func (p *productRpo) Exist(db *gorm.DB, key uint64) (*gorm.DB, bool) {
	var count int64
	tx := db.Model(&dbspo.Product{}).Where("id=?", key).Count(&count)
	return tx, count > 0
}

func (p *productRpo) ExistWithName(db *gorm.DB, name string) (*gorm.DB, bool) {
	var count int64
	tx := db.Model(&dbspo.Product{}).Where("name=?", name).Count(&count)
	return tx, count > 0
}

func (p *productRpo) FindByMasterKey(db *gorm.DB, masterKey string) (*gorm.DB, *dbspo.Product) {
	var model dbspo.Product
	return db.Model(&dbspo.Product{}).Where("master_key=?", masterKey).First(&model), &model
}

func (p *productRpo) FindById(db *gorm.DB, id uint64) (*gorm.DB, *dbspo.Product) {
	var model dbspo.Product
	return db.Model(&dbspo.Product{}).Where("id=?", id).First(&model), &model
}

type ProductBriefInfo struct {
	ID   uint64 `json:"id" gorm:"id"`
	Name string `json:"name" gorm:"name"`
}

func (p *productRpo) FindAllToBriefInfos(db *gorm.DB, companyId uint64) (*gorm.DB, []ProductBriefInfo) {
	//productBriefInfos := make([]ProductBriefInfo, 10)
	var productBriefInfos []ProductBriefInfo
	return db.Table(dbspo.Product{}.TableName()).Select("id", "name").Find(&productBriefInfos, "cid=?", companyId), productBriefInfos
}

func (p *productRpo) CountByCid(db *gorm.DB, companyId uint64) (*gorm.DB, *int64) {
	var count int64
	return db.Model(&dbspo.Product{}).Where("cid=?", companyId).Count(&count), &count
}
